// import type { UseFetchOptions } from "nuxt/app";
// import { useNuxtApp } from "#app";

// type Methods = "GET" | "POST" | "PUT" | "DELETE";

class HttpRequest {
  request(url, method, data, options = {}) {
    return new Promise((resolve, reject) => {
      const newOptions = {
        method,
        ...options,
      };
      const userStore = useStore.userStore();
      const appStore = useStore.appStore();
      const { language } = storeToRefs(appStore);
      const { $navigate } = useNuxtApp();
      // 添加更多调试信息

      newOptions.headers = {
        ...newOptions.headers,
        authorization: `Bearer ${ userStore.token }`,
        "Accept-Language": language.value || appStore.language, // 添加备用值
        "Tenant-Id": userStore.tenantId,
      };

      // 根据请求方法处理参数
      if (method === "GET" || method === "DELETE") {
        newOptions.params = data;
      } else if (method === "POST" || method === "PUT") {
        newOptions.body = data;
      }

      const nuxtApp = useNuxtApp();

      // 允许通过 options 强制指定请求方式
      let forceClient = options.forceClient || false;
      let forceServer = options.forceServer || false;

      // 确定使用哪种请求方式
      let useClientRequest = false;

      if (forceClient) {
        useClientRequest = true;
      } else if (forceServer) {
        useClientRequest = false;
      } else {
        // 自动检测：客户端且不在水合过程中
        useClientRequest = process.client && !nuxtApp.isHydrating;
      }
      // 解决非主动发起的客户端请求
      if (process.client && !nuxtApp.isHydrating) {
        newOptions.headers = {
          ...newOptions.headers,
          "Cache-Control": "no-cache, no-store, max-age=0, must-revalidate",
          "Pragma": "no-cache",
          "Expires": "0",
        };
        const ts = Date.now();
        if (method === "GET" || method === "DELETE") {
          newOptions.params = { ...(newOptions.params || {}), _t: ts };
        }
        const payload = method === "GET" || method === "DELETE"
          ? (newOptions.params || {})
          : (newOptions.body || {});
        newOptions.key = newOptions.key || `${ method }:${ url }:${ JSON.stringify(payload) }`;
      }

      const fetchMethod = useClientRequest ? nuxtApp.$request : useFetch;
      fetchMethod(url, newOptions)
        .then((res) => {
          // 处理不同环境的响应格式
          let responseData;
          if (useClientRequest) {
            // 客户端响应格式
            responseData = res;
          } else {
            // 服务端响应格式 (useFetch)
            responseData = res.data.value;
          }
          if (responseData && responseData.code === 0) {
            resolve(responseData);
          } else if (responseData && responseData.code === 400) {
            if (process.client) {
              ElMessage.error(responseData.msg || '请求参数错误');
            }
            reject(responseData);
          } else if (responseData && responseData.code === 401) {
            if (process.client) {
              ElMessage.error(responseData.msg || '请先登录');
              userStore.setToken('');
              const route = useRoute()
              $navigate({
                path: '/login',
                query: {
                  redirect: encodeURIComponent(route.fullPath)
                }
              })
              // $navigate('/login')
            }
            reject(responseData);
          }else if (responseData && responseData.code) {
            if (process.client) {
              ElMessage.error(responseData.msg || '请求失败');
            }
            reject(responseData);
          } else {
            // 处理没有 code 字段的响应
            reject(responseData);
            if (process.client) {
              ElMessage.error('服务器错误,请重试！');
            }
          }
        })
        .catch((error) => {
          this.handleError(error, resolve, reject);
        });
    });
  }

  handleError(error, resolve, reject) {
    let errorMessage = "服务器错误";
    let errorData = null;

    // 处理不同环境的错误格式
    if (error.response && error.response._data) {
      let data = error.response._data;
      if (typeof error.response._data === "string") {
        try {
          data = JSON.parse(error.response._data);
        } catch (e) {
          errorMessage = error.response._data;
        }
      }

      if (data.errors) {
        const errorMessages = [];
        for (const key in data.errors) {
          errorMessages.push(`${ data.errors[key].join(", ") }`);
        }
        errorMessage = errorMessages.join("；") || errorMessage;
      } else {
        errorMessage = data.message || data.msg || errorMessage;
      }
      errorData = data;
    } else if (error.data) {
      // 处理 useFetch 的错误格式
      errorData = error.data;
      errorMessage = error.data.message || error.data.msg || errorMessage;
    } else if (error.message) {
      errorMessage = error.message;
    }

    // 只在客户端显示错误消息
    if (process.client) {
      ElMessage.error(errorMessage);
    }

    // 处理特定的错误码
    if (errorData && [40001, 40002, 40003].includes(errorData.code)) {
      resolve(errorData);
      return;
    }

    reject(errorData || errorMessage);
  }

  // 客户端请求方法
  getClient(url, params, options = {}) {
    return this.request(url, "GET", params, { ...options, forceClient: true });
  }

  postClient(url, data, options = {}) {
    return this.request(url, "POST", data, { ...options, forceClient: true });
  }

  putClient(url, data, options = {}) {
    return this.request(url, "PUT", data, { ...options, forceClient: true });
  }

  deleteClient(url, params, options = {}) {
    return this.request(url, "DELETE", params, { ...options, forceClient: true });
  }

  // 服务端请求方法
  getServer(url, params, options = {}) {
    return this.request(url, "GET", params, { ...options, forceServer: true });
  }

  postServer(url, data, options = {}) {
    return this.request(url, "POST", data, { ...options, forceServer: true });
  }

  putServer(url, data, options = {}) {
    return this.request(url, "PUT", data, { ...options, forceServer: true });
  }

  deleteServer(url, params, options = {}) {
    return this.request(url, "DELETE", params, { ...options, forceServer: true });
  }

  // 原有的自动检测方法
  get(url, params, options) {
    return this.request(url, "GET", params, options);
  }

  post(url, data, options) {
    return this.request(url, "POST", data, options);
  }

  put(url, data, options) {
    return this.request(url, "PUT", data, options);
  }

  delete(url, params, options) {
    return this.request(url, "DELETE", params, options);
  }
}

const httpRequest = new HttpRequest();
export default httpRequest;
